package com.example.fresheveryday.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.fresheveryday.po.Log;
import com.example.fresheveryday.po.User;
import com.example.fresheveryday.restful.JsonResult;
import com.example.fresheveryday.service.LogService;
import com.example.fresheveryday.service.PermissionService;
import com.example.fresheveryday.service.RoleService;
import com.example.fresheveryday.service.UserService;
import eu.bitwalker.useragentutils.Browser;
import eu.bitwalker.useragentutils.OperatingSystem;
import eu.bitwalker.useragentutils.UserAgent;
import eu.bitwalker.useragentutils.Version;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.Set;

@RestController
public class LoginController {
    @Autowired
    UserService userService;
    @Autowired
    JavaMailSenderImpl mailSender;
    @Autowired
    RoleService roleService;
    @Autowired
    PermissionService permissionService;
    @Autowired
    LogService logService;

    String code = String.format("%04d", System.currentTimeMillis() % 10000L);
    @RequestMapping(value="/login")
    public User login(@RequestBody(required = false) Map<String,Object> map,HttpServletRequest request){
        String email = map.get("email").toString();
        String password = map.get("password").toString();
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<User>();
        userQueryWrapper.eq("email",email)
                .eq("password",password);
        User user = userService.getOne(userQueryWrapper);
        System.out.println("email" + email);
        System.out.println("password" + password);
        System.out.println("给前端的" + user);

        String ip = request.getHeader("x-forwarded-for");
        if(ip==null || ip.length()==0 || "unknown".equalsIgnoreCase(ip)){
            ip = request.getHeader("Proxy-Client-IP");
        }
        if(ip==null || ip.length()==0 || "unknown".equalsIgnoreCase(ip)){
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if(ip==null || ip.length()==0 || "unknown".equalsIgnoreCase(ip)){
            ip = request.getRemoteAddr();
        }
        if(ip.equals("0:0:0:0:0:0:0:1")){
            ip="127.0.0.1";
        }
        System.out.println("IP地址："+ip);
        String agentStr = request.getHeader("user-agent");
        System.out.println(agentStr);
        UserAgent agent = UserAgent.parseUserAgentString(agentStr);
        //浏览器
        Browser browser = agent.getBrowser();
        System.out.println("类型："+browser.getBrowserType()+
                "\n名称："+browser.getName()+
                "\n厂商："+browser.getManufacturer()+
                "\n产品系列："+browser.getGroup()+
                "\n引擎："+browser.getRenderingEngine());

        //浏览器版本
        Version version = agent.getBrowserVersion();
        if (version != null) {
            System.out.println("========================");
            System.out.println("主版本：" + version.getMajorVersion() +
                    "\n小版本：" + version.getMinorVersion() +
                    "\n完整版本：" + version.getVersion());
        }
        //操作系统
        System.out.println("========================");
        OperatingSystem os = agent.getOperatingSystem();
        System.out.println("名称："+os.getName()+
                "\n设备类型："+os.getDeviceType()+
                "\n产品系列："+os.getGroup()+
                "\n生成厂商："+os.getManufacturer());

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Log log = new Log();
        log.setUserId(String.valueOf(user.getId()));
        log.setRemark("登录");
        log.setLogContent("登录");
        log.setIpAddress(ip);
        log.setOs(os.getName());
        log.setIe(browser.getName());
        log.setCreateData(new Date());
        System.out.println(log);
        logService.saveOrUpdate(log);


        return user;
    }
    @RequestMapping("/register")
    public JsonResult register(@RequestBody String  json){
        JSONObject jsonObject = JSON.parseObject(json);
        User user = jsonObject.getObject("user", User.class);
        String code = jsonObject.getObject("code",String.class);
        String str = code;
        if(str == code){
            userService.save(user);
            return JsonResult.success("success");
        }
        else{
            return JsonResult.error("error");
        }

    }
    @RequestMapping("/email")
    public JsonResult email(String email){
        SimpleMailMessage message = new SimpleMailMessage();
        message.setSubject("天天生鲜验证码");
        message.setText("尊敬的用户您好！您的验证码为" + code + "请在5分钟内使用！");
        message.setTo(email);
        message.setFrom("1113750039@qq.com");
        mailSender.send(message);
        return JsonResult.success("success");
    }

    @RequestMapping("/dev/login")
    public User login(@RequestBody Map<String,String> map, HttpServletResponse rsp){
        String email = map.get("email").toString();
        String password = map.get("password").toString();
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<User>();
        userQueryWrapper.eq("email",email)
                .eq("password",password);
        User user = userService.getOne(userQueryWrapper);
        System.out.println(roleService.queryRoleNameByUserId(String.valueOf(user.getId())));
        if(user == null){
            return user;
        }
        else if(roleService.queryRoleNameByUserId(String.valueOf(user.getId())).contains("超级管理员")){
            return user;
        }
        else {
            return null;
        }

//        try{
//            userService.checkLogin(email,password);
//            System.out.println("登录成功");
//        } catch (Exception e) {
//            System.out.println("登录失败");
//            e.printStackTrace();
//
//            Set<String> strings = roleService.queryRoleNameByUserId(user.getId());
//
//        }
    }
}
